package com.example.badminton.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.badminton.entity.Booking;
import com.example.badminton.mapper.BookingMapper;
import com.example.badminton.service.BookingService;
import com.example.badminton.service.CourtService;
import com.example.badminton.entity.Court;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class BookingServiceImpl extends ServiceImpl<BookingMapper, Booking> implements BookingService {

    @Autowired
    private CourtService courtService;

    @Override
    public List<Booking> getBookingsByUserId(Long userId) {
        QueryWrapper<Booking> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.orderByDesc("create_time");
        return this.list(queryWrapper);
    }

    @Override
    public List<Booking> getBookingsByCourtId(Long courtId) {
        QueryWrapper<Booking> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("court_id", courtId);
        queryWrapper.orderByDesc("create_time");
        return this.list(queryWrapper);
    }

    @Override
    public Map<Long, Map<String, String>> getAvailabilityByDate(String dateStr) {
        // 时间段定义
        String[] slots = {
            "08:00-09:00", "09:00-10:00", "10:00-11:00", "11:00-12:00",
            "12:00-13:00", "13:00-14:00", "14:00-15:00", "15:00-16:00",
            "16:00-17:00", "17:00-18:00", "18:00-19:00", "19:00-20:00",
            "20:00-21:00", "21:00-22:00"
        };
        // 获取所有球场
        List<Court> courts = courtService.list();
        // 查询当天所有预定
        Date date;
        try {
            date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
        } catch (Exception e) {
            throw new RuntimeException("日期格式错误");
        }
        List<Booking> bookings = this.lambdaQuery()
            .eq(Booking::getDate, date)
            .in(Booking::getStatus, 0, 1) // 只统计未取消的
            .list();
        // 构建map
        Map<Long, Map<String, String>> result = new HashMap<>();
        for (Court court : courts) {
            Map<String, String> slotMap = new HashMap<>();
            for (String slot : slots) {
                slotMap.put(slot, "free");
            }
            result.put(court.getId(), slotMap);
        }
        for (Booking booking : bookings) {
            Long courtId = booking.getCourtId();
            String slot = booking.getTimeSlot();
            if (result.containsKey(courtId) && result.get(courtId).containsKey(slot)) {
                result.get(courtId).put(slot, "booked");
            }
        }
        return result;
    }
} 